﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CampusSite.Models;
namespace CampusSite.Security
{

        [AttributeUsage(AttributeTargets.All, Inherited = true)]
        public class RoleAuthorizeAttribute : AuthorizeAttribute
        {
            #region Public Methods

            public RoleAuthorizeAttribute(params string[] roles)            
            {                
                this.Roles = roles;
            }

            public string[] Roles { get; set; }

            //public string[] Roles { get; set; }

            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                var isAuthorized = base.AuthorizeCore(httpContext);
                if (!isAuthorized)
                    return false;

                string username = httpContext.User.Identity.Name;

                UserRepository repo = new UserRepository();

                return repo.IsUserInRole(username, this.Roles);
            }

            //public override bool IsAuthorized(HttpContextBase httpContext)
            //{
            //    if (!httpContext.User.Identity.IsAuthenticated)
            //    {
            //        return false;
            //    }
                
            //    //aca tengo que poner la logica para validar si el usuario tiene
            //    //un rol que tiene autorizacion al control
            //    //

            //    //var pulsarPrincipal = this.GetPulsarPrincipal(httpContext);
            //    //if (this.Roles.Length > 0 && !pulsarPrincipal.IsInAnyRole(this.Roles))
            //    //{
            //    //    return false;
            //    //}
            //    return true;
            //}
            #endregion      
    }



        public sealed class LogonAuthorize : AuthorizeAttribute
        {
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
                if (!skipAuthorization)
                {
                    base.OnAuthorization(filterContext);
                }
            }
        }

        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
                    AllowMultiple = false, Inherited = true)]
        public sealed class AllowAnonymousAttribute : Attribute { }


}